using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;


namespace homeworkhero
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class Enemy : CollidableSprite
    {
        private const float ENEMYSPEEDX = 2.5f;
        private const float ENEMYSPEEDY = 0.1f;

        Player target;
        TimeSpan timeUntilFindNewTarget = TimeSpan.Zero;

        public Enemy(Stage s, AnimationSet animSet, Vector2 spawn, int health)
            : base(s, CollidableSprite.CollidableSpriteType.ENEMY, animSet)
        {
            setPosition(spawn);
            this.health = health;
            target = s.getPlayers().First.Value;
        }

        public override void update(GameTime gameTime)
        {
            if(!isDying() && !isDead()) {
                LinkedList<Player> players = stage.getPlayers();
                seekPlayer(players, gameTime);
            } else {
                setVelocity(Vector2.Zero);
            }

            base.update(gameTime);
        }

        public void seekPlayer(LinkedList<Player> players, GameTime gameTime)
        {
            Vector2 playerPosition = target.getPosition();

            if (base.getPosition().X > playerPosition.X)
            {
                base.setVelocityX(-ENEMYSPEEDX);
            }
            else if (base.getPosition().X < playerPosition.X)
            {
                base.setVelocityX(ENEMYSPEEDX);
            }

            if (base.getPosition().Y < playerPosition.Y)
            {
                base.setVelocityY(ENEMYSPEEDY);
            }
            else if (base.getPosition().Y > playerPosition.Y)
            {
                base.setVelocityY(-ENEMYSPEEDY);
            }
        }

        public override int getDamage()
        {
            return 5;
        }

        public override Vector2 getScreenPosition()
        {
            Vector2 realPos = getPosition();

            realPos.X = (Game1.SCREENWIDTH / 3.0f) - stage.getPlayerX() + realPos.X;
            realPos.Y = Game1.SCREENHEIGHT - (realPos.Y * Game1.LAYERHEIGHT);

            return realPos;
        }

        public Enemy copyEnemy()
        {
            Enemy newEnemy = new Enemy(base.stage, base.animSet.copy(), Vector2.Zero, health);
            return newEnemy;
        }

    }
}
